package cn.gov.cbrc.core.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

public class ConnectionUtil {
	
	private static ThreadLocal<Map<String,Connection>> tconnMap = new ThreadLocal<Map<String,Connection>>();
	
	/**
	 * <p>方法描述: 获取连接</p>
	 * <p>方法备注: </p>
	 * @param jndiName
	 * @return
	 * @throws SQLException
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 10, 2014 10:00:04 AM</p>
	 *
	 */
	public static Connection getConnection(String jndiName) throws SQLException {
		Map<String,Connection> cMap = tconnMap.get();
		if(cMap == null){
			cMap = new HashMap<String, Connection>();
			tconnMap.set(cMap);
		}
		Connection conn = cMap.get(jndiName);
		if(conn==null){
			DataSource ds = DataSourceUtil.getDataSource(jndiName);
			if(ds !=null ){
				conn = ds.getConnection();
				cMap.put(jndiName, conn);
			}
		}
		return conn;
	}
	
	public static Connection getConnectionQuiet(String jndiName) {
		Map<String,Connection> cMap = tconnMap.get();
		if(cMap == null){
			cMap = new HashMap<String, Connection>();
		}
		return cMap.get(jndiName);
	}
	
	/**
	 * <p>方法描述: 将某个连接移除</p>
	 * <p>方法备注: </p>
	 * @param jndiName
	 * @throws SQLException
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 10, 2014 10:02:36 AM</p>
	 *
	 */
	public static void removeConnection(String jndiName) {
		Map<String,Connection> cMap = tconnMap.get();
		if(cMap == null){
			cMap = new HashMap<String, Connection>();
			tconnMap.set(cMap);
		}
		cMap.remove(jndiName);
	}
	
	public static List<Connection> getAllConnection() {
		Map<String,Connection> cMap = tconnMap.get();
		if(cMap == null){
			cMap = new HashMap<String, Connection>();
		}
		return new ArrayList<Connection>(cMap.values());
	}
	
	/**
	 * <p>方法描述: 清除所有连接</p>
	 * <p>方法备注: </p>
	 * @throws SQLException
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 10, 2014 10:03:02 AM</p>
	 *
	 */
	public static void removeAllConnection() {
		tconnMap.remove();
	}
	
	
}
